package com.software.fanfan.dao.impl;

import com.software.fanfan.dao.UserDao;
import com.software.fanfan.entity.model.UserModel;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManagerFactory;
import java.util.List;
import java.util.Map;

/**
 * UserDao
 *
 * Created by shiyanfei on 2018-01-09.
 */
@Repository
public class UserDaoImpl implements UserDao{

    private SessionFactory sessionFactory;
    private JdbcTemplate jdbcTemplate;
    public UserDaoImpl() {
    }

    // TODO sessionFactory无法注入
    // 解答：spring boot 自动注入的是EntityManagerFactory，而不是sessionFactory
    @Autowired
    public UserDaoImpl(JdbcTemplate jdbcTemplate, EntityManagerFactory entityManagerFactory){
        this.jdbcTemplate = jdbcTemplate;
        this.sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
    }

    private Session getCurrentSession(){
        return sessionFactory.getCurrentSession();
    }

    public String create(Object o){
        return getCurrentSession().save(o).toString();
    }

    public void update(Object o){
        getCurrentSession().update(o);
    }

    /**
     * 该方法是一个预留的方法
     *
     * @param entityName 表名
     * @param o 更新的对象
     */
    public void updata(String entityName,Object o){
        getCurrentSession().save(entityName,o);
    }

    // 测试jdbcTemplate
    public List<Map<String, Object>> test(){
        List<Map<String, Object>> listMap =  jdbcTemplate.queryForList("");
        return listMap;
    }

    @Override
    public UserModel getUserByLoginId(String loginId, String password) {
        return null;
    }


}
